<?php 
class ImageController extends ApiController {
	
	/**
	 * @return array action filters
	 */
	public function filters() {
		$arr = array(
			'postOnly + add, deleteMulti'
		);
		return array_merge(parent::filters(), $arr);
	}

	/**
	 * Upload image
	 *
	 * @return string
	 */
	public function actionAdd() {
		$model=new ImageUploadForm();
		if (isset($_FILES['file'])) {
			$model->file = $_FILES['file'];
			$model->file = CUploadedFile::getInstanceByName('file');
			
			if ($model->validate()) {
				$result = $model->saveUploadImage();
				$this->_sendSuccess($result);
			} else {
				$this->_sendError($model->getErrors(), 400);
			}
		}
		$this->_sendError('Your request is in valid', 400);
	}
	
	public function actionList() {
		$paging = array_merge(array(
			'limit'=>40,
			'offset'=>0
		), $_GET);
		$c = new CDbCriteria();
		$c->limit = $paging['limit'];
		$c->offset = $paging['offset'];
		$models = Image::model()->findAll($c);
		$result = array();
		foreach($models as $model) {
			$data = $model->attributes;
			$data['url'] = Yii::app()->getBaseUrl(true) . $model->path;
			$result[] = $data;
		}
		$this->_sendSuccess($result);
	}
	
	public function actionDelete() {
		if (isset($_GET['id']))
			$model=Image::model()->findByPk($_GET['id']);
		
		if (isset($_GET['path']))
			$model=Image::model()->findByAttributes(array('path'=>$_GET['path']));
		
		if(!$model)
			$this->_sendError('Your request is in valid', 400);
		$model->delete();
		$this->_sendSuccess('1');
	}
	
	public function actionDeleteMulti() {
		if (isset($_POST['ids'])) {
			$ids = $_POST['ids'];
			$models=Image::model()->findAll("id IN (". implode(',', $ids) .")");
		}
		
		if (isset($_POST['paths'])) {
			$paths = $_POST['paths'];
			foreach($paths as &$p)
				$p = "'$p'";
			$models=Image::model()->findAll("path IN (". implode(',', $paths) .")");
		}

		foreach($models as $model) {
			$model->delete();
		}
		$this->_sendSuccess('1');
	}
}